import axios from 'axios';
import type {AxiosInstance, AxiosResponse} from 'axios';

const axiosInstance: AxiosInstance = axios.create({
    baseURL: 'http://127.0.0.1:5001',
    timeout: 5000,
});
import {ElMessage} from 'element-plus'


const getMsg = (status: number): string => {
    switch (status) {
        case 400:
            return "请求错误"
        case 401:
            return "未授权，请登录"
        case 403:
            return "拒绝访问"
        case 404:
            return "请求地址出错"
        case 408:
            return "请求超时"
        case 500:
            return "服务器内部错误"
        case 501:
            return "服务未实现"
        case 502:
            return "网关错误"
        case 503:
            return "服务不可用"
        case 504:
            return "网关超时"
        case 505:
            return "HTTP版本不受支持"
        default:
            return "未知错误"
    }
}

// 添加请求拦截器
axiosInstance.interceptors.request.use(
    (config) => {
        // 在发送请求之前做些什么
        return config;
    },
    (error: any) => {
        // 处理请求错误
        return Promise.reject(error);
    },
);
// 添加响应拦截器
axiosInstance.interceptors.response.use(
    (response: AxiosResponse) => {
        // 对响应数据做点什么
        if (response.status !== 200) {
            // Element 弹窗
            ElMessage.error(getMsg(response.status))
            return
        }
        return response.data;
    },
    (error: any) => {
        // 处理响应错误
        return Promise.reject(error);
    },
);
export default axiosInstance